document.addEventListener('DOMContentLoaded', function() {
    const promptInput = document.getElementById('prompt');
    const styleSelect = document.getElementById('style');
    const sizeSelect = document.getElementById('size');
    const relevanceSelect = document.getElementById('relevance');
    const generateBtn = document.getElementById('generate-btn');
    const loadingElement = document.getElementById('loading');
    const imageContainer = document.getElementById('image-container');
    const historyContainer = document.getElementById('history-container');
    
    // 存储历史记录
    let history = JSON.parse(localStorage.getItem('aiImageHistory')) || [];
    
    // 从提示词中提取关键词
    function extractKeywords(prompt) {
        // 移除标点符号和特殊字符
        const cleanPrompt = prompt.replace(/[^\w\s\u4e00-\u9fa5]/g, ' ');
        
        // 分词
        const words = cleanPrompt.split(/\s+/);
        
        // 常见的停用词
        const stopWords = ['的', '了', '和', '与', '或', '在', '是', '我', '你', '他', '她', '它', '们', '这', '那', '有', '个', '一个', '一张', '想要', '生成', '请', '帮我', 'the', 'a', 'an', 'and', 'or', 'in', 'on', 'at', 'to', 'for', 'with', 'by', 'about', 'like', 'through', 'over', 'before', 'between', 'after', 'since', 'without', 'under', 'within', 'along', 'following', 'across', 'behind', 'beyond', 'plus', 'except', 'but', 'up', 'out', 'around', 'down', 'off', 'above', 'near'];
        
        // 过滤停用词和短词
        const filteredWords = words.filter(word => {
            return word.length > 1 && !stopWords.includes(word.toLowerCase());
        });
        
        // 返回最多5个关键词
        return filteredWords.slice(0, 5);
    }
    
    // 显示历史记录
    function renderHistory() {
        historyContainer.innerHTML = '';
        
        history.slice().reverse().forEach((item, index) => {
            const historyItem = document.createElement('div');
            historyItem.className = 'history-item';
            
            // 创建图片元素
            const img = document.createElement('img');
            img.alt = "生成的图片";
            
            // 添加错误处理
            img.onerror = function() {
                console.log('历史记录图片加载失败');
                this.src = 'data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22160%22%20height%3D%22160%22%20viewBox%3D%220%200%20160%20160%22%3E%3Cg%20fill%3D%22%2300ccff%22%3E%3Cpath%20d%3D%22M80%2010L10%20150h140L80%2010zm0%2030l50%2090H30l50-90z%22%2F%3E%3Ccircle%20cx%3D%2280%22%20cy%3D%22125%22%20r%3D%228%22%2F%3E%3Cpath%20d%3D%22M76%2070v35h8V70h-8z%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E';
                this.style.padding = '10px';
                this.style.backgroundColor = 'rgba(10, 14, 23, 0.8)';
            };
            
            img.src = item.imageUrl;
            
            // 创建提示词容器
            const promptDiv = document.createElement('div');
            promptDiv.className = 'prompt';
            promptDiv.textContent = item.prompt;
            
            // 添加到历史项
            historyItem.appendChild(img);
            historyItem.appendChild(promptDiv);
            
            historyItem.addEventListener('click', () => {
                promptInput.value = item.prompt;
                styleSelect.value = item.style;
                sizeSelect.value = item.size;
                // 如果历史记录中有相关度信息，则恢复它
                if (item.relevance) {
                    relevanceSelect.value = item.relevance;
                }
                
                // 滚动到顶部
                window.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            });
            
            historyContainer.appendChild(historyItem);
        });
    }
    
    // 使用MCP服务生成图片
    function generateAIImages(prompt, style, size, relevance, count = 4) {
        return new Promise((resolve) => {
            // 显示加载状态
            setTimeout(() => {
                // 从提示词中提取关键词和分析意图
                const keywords = extractKeywords(prompt);
                
                // 根据风格映射到MCP的风格参数
                const stylePrompts = {
                    'realistic': 'photorealistic, detailed, high resolution',
                    'cartoon': 'cartoon style, vibrant colors, animation',
                    'abstract': 'abstract art, geometric shapes, modern art',
                    'digital': 'digital art, futuristic, sci-fi, technology',
                    'oil': 'oil painting, classical art, detailed brushstrokes'
                };
                
                const stylePrompt = stylePrompts[style] || stylePrompts['realistic'];
                
                // 根据相关度调整提示词
                let fullPrompt = prompt;
                
                // 添加风格描述
                fullPrompt += `, ${stylePrompt}`;
                
                // 根据相关度调整关键词和创意程度
                if (relevance === 'high') {
                    // 高相关度：严格匹配描述，添加更多原始关键词
                    fullPrompt += ', exact match, precise, accurate representation';
                } else if (relevance === 'medium') {
                    // 中相关度：适度发挥，保持主题但允许一定创意
                    fullPrompt += ', creative interpretation, inspired by';
                } else if (relevance === 'low') {
                    // 低相关度：创意发挥，只保留核心概念
                    fullPrompt += ', artistic freedom, loosely based on, creative concept';
                }
                
                // 添加质量描述
                fullPrompt += ', high quality, detailed';
                
                console.log('正在调用MCP图像生成服务...');
                
                // 模拟调用MCP服务
                // 在实际应用中，这里应该使用use_mcp_tool工具调用真实的MCP服务
                /*
                const result = await use_mcp_tool({
                    server_name: "image-generation-mcp",
                    tool_name: "generate_images",
                    arguments: {
                        prompt: fullPrompt,
                        style: style,
                        size: size,
                        count: count
                    }
                });
                */
                
                // 调整尺寸，确保在一行中能显示多张图片
                const width = size === 'small' ? 400 : size === 'medium' ? 500 : 600;
                const height = width;
                
                // 模拟MCP返回的图片URL
                const imageUrls = [];
                
                // 使用更智能的图片分类系统
                const imageCategories = getMCPImageCategories(prompt, style, keywords, relevance);
                const category = imageCategories.join(',');
                
                // 生成多张图片
                for (let i = 0; i < count; i++) {
                // 使用Unsplash API获取更精准的图片，添加备用图片源
                const imageUrl = `https://source.unsplash.com/featured/${width}x${height}/?${category}&sig=${Date.now() + i}`;
                // 备用图片源，当主图片源加载失败时使用
                const fallbackImageUrl = `https://picsum.photos/${width}/${height}?random=${Date.now() + i}`;
                imageUrls.push({
                    primary: imageUrl,
                    fallback: fallbackImageUrl
                });
                }
                
                // 返回图片URL和使用的参数
                resolve({
                    imageUrls: imageUrls,
                    usedKeywords: [
                        `MCP提示词: ${fullPrompt}`,
                        `图像类别: ${imageCategories.join(', ')}`,
                        `风格: ${style}`,
                        `尺寸: ${size === 'small' ? '512x512' : size === 'medium' ? '1024x1024' : '1792x1024'}`
                    ]
                });
            }, 4000); // 模拟4秒的MCP处理时间
        });
    }
    
    // MCP图像分类系统
    function getMCPImageCategories(prompt, style, keywords, relevance) {
        const promptLower = prompt.toLowerCase();
        const categories = [];
        
        // 高级内容分析
        if (promptLower.includes('人物') || promptLower.includes('人像') || promptLower.includes('portrait')) {
            if (promptLower.includes('女') || promptLower.includes('woman') || promptLower.includes('girl')) {
                categories.push('woman', 'portrait', 'female');
                
                // 更细致的分析
                if (promptLower.includes('年轻') || promptLower.includes('young')) {
                    categories.push('young');
                }
                if (promptLower.includes('微笑') || promptLower.includes('smile')) {
                    categories.push('smiling');
                }
            } else if (promptLower.includes('男') || promptLower.includes('man') || promptLower.includes('boy')) {
                categories.push('man', 'portrait', 'male');
                
                if (promptLower.includes('胡子') || promptLower.includes('beard')) {
                    categories.push('beard');
                }
            } else {
                categories.push('people', 'portrait');
            }
            
            // 分析场景
            if (promptLower.includes('室内') || promptLower.includes('indoor')) {
                categories.push('indoor');
            } else if (promptLower.includes('室外') || promptLower.includes('outdoor')) {
                categories.push('outdoor');
            }
        } else if (promptLower.includes('风景') || promptLower.includes('自然') || promptLower.includes('landscape')) {
            if (promptLower.includes('山') || promptLower.includes('mountain')) {
                categories.push('mountains', 'landscape');
                
                if (promptLower.includes('雪') || promptLower.includes('snow')) {
                    categories.push('snow');
                }
            } else if (promptLower.includes('海') || promptLower.includes('ocean') || promptLower.includes('beach')) {
                categories.push('ocean', 'beach', 'sea');
                
                if (promptLower.includes('日落') || promptLower.includes('sunset')) {
                    categories.push('sunset');
                }
            } else if (promptLower.includes('森林') || promptLower.includes('forest')) {
                categories.push('forest', 'trees', 'nature');
                
                if (promptLower.includes('雾') || promptLower.includes('fog')) {
                    categories.push('foggy');
                }
            } else {
                categories.push('landscape', 'nature');
            }
            
            // 分析时间
            if (promptLower.includes('夜') || promptLower.includes('night')) {
                categories.push('night');
            } else if (promptLower.includes('日出') || promptLower.includes('sunrise')) {
                categories.push('sunrise');
            }
        } else if (promptLower.includes('动物') || promptLower.includes('宠物') || promptLower.includes('animal')) {
            if (promptLower.includes('猫') || promptLower.includes('cat')) {
                categories.push('cat', 'kitten', 'feline');
            } else if (promptLower.includes('狗') || promptLower.includes('dog')) {
                categories.push('dog', 'puppy', 'canine');
            } else if (promptLower.includes('鸟') || promptLower.includes('bird')) {
                categories.push('bird', 'avian');
            } else {
                categories.push('animal', 'wildlife');
            }
            
            // 分析动作
            if (promptLower.includes('奔跑') || promptLower.includes('running')) {
                categories.push('running');
            } else if (promptLower.includes('睡觉') || promptLower.includes('sleeping')) {
                categories.push('sleeping');
            }
        } else if (promptLower.includes('建筑') || promptLower.includes('城市') || promptLower.includes('architecture')) {
            if (promptLower.includes('现代') || promptLower.includes('modern')) {
                categories.push('modern', 'architecture', 'skyscraper');
            } else if (promptLower.includes('古代') || promptLower.includes('古典') || promptLower.includes('classical')) {
                categories.push('classical', 'architecture', 'historical');
            } else if (promptLower.includes('城市') || promptLower.includes('city')) {
                categories.push('cityscape', 'urban');
                
                if (promptLower.includes('夜景') || promptLower.includes('night')) {
                    categories.push('night', 'lights');
                }
            } else {
                categories.push('architecture', 'building');
            }
        } else if (promptLower.includes('食物') || promptLower.includes('美食') || promptLower.includes('food')) {
            categories.push('food', 'cuisine', 'gourmet');
            
            if (promptLower.includes('甜点') || promptLower.includes('dessert')) {
                categories.push('dessert', 'sweet');
            } else if (promptLower.includes('蔬菜') || promptLower.includes('vegetable')) {
                categories.push('vegetable', 'healthy');
            }
        } else if (promptLower.includes('科技') || promptLower.includes('技术') || promptLower.includes('tech')) {
            categories.push('technology', 'digital', 'futuristic');
        } else {
            // 默认使用关键词
            categories.push(...keywords);
        }
        
        // 根据风格添加额外的类别
        if (style === 'cartoon') {
            categories.push('cartoon', 'animation', 'illustrated');
        } else if (style === 'abstract') {
            categories.push('abstract', 'art', 'geometric');
        } else if (style === 'digital') {
            categories.push('digital', 'futuristic', 'scifi');
        } else if (style === 'oil') {
            categories.push('painting', 'art', 'classical');
        } else {
            categories.push('photorealistic', 'detailed');
        }
        
        // 根据相关度调整返回的类别数量和精确度
        let finalCategories = [...new Set(categories)];
        
        if (relevance === 'high') {
            // 高相关度：返回更多精确的类别，确保匹配度高
            return finalCategories.slice(0, 7);
        } else if (relevance === 'medium') {
            // 中相关度：返回适中数量的类别
            return finalCategories.slice(0, 5);
        } else {
            // 低相关度：返回较少的类别，增加创意空间
            return finalCategories.slice(0, 3);
        }
    }
    
    // 生成图片按钮点击事件
    generateBtn.addEventListener('click', async function() {
        const prompt = promptInput.value.trim();
        const style = styleSelect.value;
        const size = sizeSelect.value;
        const relevance = relevanceSelect.value;
        
        if (!prompt) {
            alert('请输入图片描述');
            return;
        }
        
        // 显示加载状态
        loadingElement.style.display = 'flex';
        imageContainer.innerHTML = '';
        generateBtn.disabled = true;
        
        try {
            // 调用AI图片生成函数，生成4张图片
            const result = await generateAIImages(prompt, style, size, relevance, 4);
            const imageUrls = result.imageUrls;
            const usedKeywords = result.usedKeywords;
            
            // 创建图片选择区域
            const selectionContainer = document.createElement('div');
            selectionContainer.className = 'image-selection';
            
            // 添加提示文字和使用的关键词
            const selectionTitle = document.createElement('p');
            selectionTitle.className = 'selection-title';
            selectionTitle.textContent = '请从以下4张图片中选择您喜欢的图片：';
            imageContainer.appendChild(selectionTitle);
            
            // 显示使用的关键词
            const keywordsInfo = document.createElement('p');
            keywordsInfo.className = 'keywords-info';
            keywordsInfo.textContent = `使用的关键词: ${usedKeywords.join(', ')}`;
            imageContainer.appendChild(keywordsInfo);
            
            // 为每张图片创建元素
            imageUrls.forEach((imageSource, index) => {
                // 创建图片容器
                const imgContainer = document.createElement('div');
                imgContainer.className = 'image-item';
                
                // 创建加载指示器
                const loadingIndicator = document.createElement('div');
                loadingIndicator.className = 'image-loading';
                loadingIndicator.innerHTML = '<div class="spinner"></div><p>加载中...</p>';
                imgContainer.appendChild(loadingIndicator);
                
                // 创建图片元素
                const img = document.createElement('img');
                img.alt = `${prompt} - 选项 ${index + 1}`;
                img.dataset.index = index;
                
                // 添加图片加载错误处理
                img.onerror = function() {
                    console.log('主图片加载失败，尝试加载备用图片');
                    // 如果主图片加载失败，尝试加载备用图片
                    this.src = imageSource.fallback;
                    
                    // 如果备用图片也加载失败
                    this.onerror = function() {
                        console.log('备用图片也加载失败，显示错误信息');
                        loadingIndicator.innerHTML = '<p style="color: red;">图片加载失败</p>';
                        // 添加重试按钮
                        const retryBtn = document.createElement('button');
                        retryBtn.className = 'select-btn';
                        retryBtn.textContent = '重试加载';
                        retryBtn.style.marginTop = '10px';
                        retryBtn.onclick = function() {
                            // 重新加载图片
                            img.src = imageSource.primary + '&retry=' + new Date().getTime();
                            loadingIndicator.innerHTML = '<div class="spinner"></div><p>重新加载中...</p>';
                        };
                        loadingIndicator.appendChild(retryBtn);
                    };
                };
                
                // 图片加载完成时隐藏加载指示器
                img.onload = function() {
                    loadingIndicator.style.display = 'none';
                    img.style.display = 'block';
                };
                
                // 设置图片源
                img.src = imageSource.primary;
                img.style.display = 'none'; // 初始隐藏图片，直到加载完成
                
                // 创建选择按钮
                const selectBtn = document.createElement('button');
                selectBtn.className = 'select-btn';
                selectBtn.textContent = `选择图片 ${index + 1}`;
                
                // 添加选择事件
                selectBtn.addEventListener('click', function() {
                    // 添加到历史记录
                    const historyItem = {
                        prompt,
                        style,
                        size,
                        relevance,
                        imageUrl: img.src, // 使用当前显示的图片URL（可能是主URL或备用URL）
                        timestamp: new Date().toISOString()
                    };
                    
                    history.push(historyItem);
                    
                    // 限制历史记录数量为20条
                    if (history.length > 20) {
                        history.shift();
                    }
                    
                    // 保存到本地存储
                    localStorage.setItem('aiImageHistory', JSON.stringify(history));
                    
                    // 更新历史记录显示
                    renderHistory();
                    
                    // 显示选择成功消息
                    alert('已将选中的图片添加到历史记录！');
                });
                
                // 将图片和按钮添加到容器
                imgContainer.appendChild(img);
                imgContainer.appendChild(selectBtn);
                
                // 添加到图片容器
                imageContainer.appendChild(imgContainer);
            });
            
        } catch (error) {
            console.error('生成图片失败:', error);
            imageContainer.innerHTML = '<p style="color: red;">生成图片失败，请重试</p>';
        } finally {
            // 隐藏加载状态
            loadingElement.style.display = 'none';
            generateBtn.disabled = false;
        }
    });
    
    // 初始化显示历史记录
    renderHistory();
});